package com.chao.lease.web.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chao.lease.common.constant.RedisConstant;
import com.chao.lease.common.exception.LeaseException;
import com.chao.lease.common.login.LoginUser;
import com.chao.lease.common.login.LoginUserHolder;
import com.chao.lease.common.result.ResultCodeEnum;
import com.chao.lease.common.utils.CodeUtil;
import com.chao.lease.common.utils.JwtUtil;
import com.chao.lease.model.entity.UserInfo;
import com.chao.lease.model.enums.BaseStatus;
import com.chao.lease.web.app.mapper.UserInfoMapper;
import com.chao.lease.web.app.service.LoginService;
import com.chao.lease.web.app.service.SmsService;
import com.chao.lease.web.app.vo.user.LoginVo;
import com.chao.lease.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public void getSMSCode(String phone) {

        //1. 检查手机号码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        String code = CodeUtil.getCodeRandom(6);
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        // 防止频繁发送验证码
        Boolean b = stringRedisTemplate.hasKey(key);
        if(b){
            Long ttl = stringRedisTemplate.getExpire(key,TimeUnit.SECONDS);
            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC - ttl < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        smsService.sendCode(phone,code);
        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
//        - 前端发送手机号码`phone`和接收到的短信验证码`code`到后端。
        String code = loginVo.getCode();
        String phone = loginVo.getPhone();
//        - 首先校验`phone`和`code`是否为空，若为空，直接响应`手机号码为空`或者`验证码为空`，若不为空则进入下步判断。
        if(phone == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if(code == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
//        - 根据`phone`从Redis中查询之前保存的验证码，若查询结果为空，则直接响应`验证码已过期` ，若不为空则进入下一步判断。
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String data_key = stringRedisTemplate.opsForValue().get(key);
        if(data_key == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
//        - 比较前端发送的验证码和从Redis中查询出的验证码，若不同，则直接响应`验证码错误`，若相同则进入下一步判断。
        if(!code.equals(data_key)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
//        - 使用`phone`从数据库中查询用户信息，若查询结果为空，则创建新用户，并将用户保存至数据库，然后进入下一步判断。
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,phone);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if(userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+loginVo.getPhone().substring(7));
            userInfoMapper.insert(userInfo);

        } else{
            // - 判断用户是否被禁用，若被禁，则直接响应`账号被禁用`，否则进入下一步。
            if(userInfo.getStatus() == BaseStatus.DISABLE){
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }
        }
        return JwtUtil.createToken(userInfo.getId(),phone);

    }

    @Override
    public UserInfoVo info() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        UserInfo userInfo = userInfoMapper.selectById(loginUser.getUserId());
        return new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
    }
}
